import requests
import json
import pandas as pd
import uuid
import os
import sys
import time
from typing import Dict, List, Any

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

# from common.train_dict import classify_problem, get_dict_name  # 导入字典查询函数
# from common.person_dict import process_persons_list  # 导入人员字典处理模块
# from save.net_save_nofyrs import save_to_txt, get_last_position, save_position, POSITION_PATH  # 导入保存相关的函数


# 设置请求超时时间（秒）
REQUEST_TIMEOUT = 300

# 设置Excel文件名
EXCEL_FILE = "wangluojian.xlsx"

# 设置API地址
API_URL = "http://localhost:9000/api/getNetLetters"

def process_person_info(name: str, **kwargs) -> Dict[str, str]:
    """处理人员信息"""
    return {
        "bh": str(uuid.uuid4()).replace("-", ""),
        "mc": name.strip(),
        **{k: v.strip() for k, v in kwargs.items() if v}
    }

def process_persons_list(names: str, **kwargs) -> List[Dict[str, str]]:
    """处理人员列表"""
    if not pd.isna(names):
        name_list = str(names).split(";")
        return [process_person_info(name, **kwargs) for name in name_list if name.strip()]
    return []

def prepare_request_data(row: pd.Series) -> Dict[str, Any]:
    """准备请求数据"""
    # 处理反映人信息
    fyrs = process_persons_list(row["反映人姓名"])
    
    # 处理被反映人信息
    bfyrs = []
    if pd.notna(row["被反映人姓名"]):
        bfyr_names = str(row["被反映人姓名"]).split(";")
        bfyr_zw = str(row["被反映人职务"]).split(";") if pd.notna(row["被反映人职务"]) else [""] * len(bfyr_names)
        bfyr_zj = str(row["被反映人职级"]).split(";") if pd.notna(row["被反映人职级"]) else [""] * len(bfyr_names)
        bfyr_dwhdz = str(row["被反映人单位或地址"]).split(";") if pd.notna(row["被反映人单位或地址"]) else [""] * len(bfyr_names)
        
        # 确保所有列表长度一致
        max_len = max(len(bfyr_names), len(bfyr_zw), len(bfyr_zj), len(bfyr_dwhdz))
        bfyr_zw.extend([""] * (max_len - len(bfyr_zw)))
        bfyr_zj.extend([""] * (max_len - len(bfyr_zj)))
        bfyr_dwhdz.extend([""] * (max_len - len(bfyr_dwhdz)))
        
        for i, name in enumerate(bfyr_names):
            if name.strip():
                bfyrs.append(process_person_info(
                    name,
                    zw=bfyr_zw[i],
                    zj=bfyr_zj[i],
                    dwhdz=bfyr_dwhdz[i]
                ))

    # 处理初次件信息
    cfj = []
    if pd.notna(row["初次件"]):
        cfj.append({
            "bh": str(uuid.uuid4()).replace("-", ""),
            "wtxx": {
                "yjms": str(row["初次件"])
            }
        })

    return {
        "bh": str(row["信访举报件编号"]),
        "caseIntruction": str(row["原件描述"]),
        "fyrs": fyrs,
        "bfyrs": bfyrs,
        "cfj": cfj
    }

def send_request(data: Dict[str, Any], index: int) -> bool:
    """发送请求并处理响应"""
    print(f"\n处理第 {index + 1} 条数据:")
    print("发送请求数据:")
    print(json.dumps(data, ensure_ascii=False, indent=2))
    
    try:
        response = requests.post(
            API_URL,
            json=data,
            timeout=REQUEST_TIMEOUT
        )
        
        # 检查响应状态码
        response.raise_for_status()
        
        # 解析JSON响应
        result = response.json()
        print("\n响应状态码:", response.status_code)
        print("响应内容:")
        print(json.dumps(result, ensure_ascii=False, indent=2))
        
        return result.get("success") == "true"
        
    except requests.exceptions.Timeout:
        print(f"请求超时（{REQUEST_TIMEOUT}秒），跳过当前数据")
        return False
    except requests.exceptions.RequestException as e:
        print(f"请求错误: {str(e)}")
        return False
    except json.JSONDecodeError as e:
        print("JSON解析错误:", str(e))
        print("原始响应内容:", response.text)
        return False

def main():
    """主函数"""
    try:
        # 读取Excel文件
        df = pd.read_excel(EXCEL_FILE, sheet_name="Sheet1")
        
        # 遍历每一行数据
        for index, row in df.iterrows():
            # 准备请求数据
            request_data = prepare_request_data(row)
            
            # 发送请求
            success = send_request(request_data, index)
            
            # 如果请求失败，等待一段时间后继续
            if not success:
                time.sleep(5)  # 失败后等待5秒再继续
                
    except FileNotFoundError:
        print(f"错误：找不到{EXCEL_FILE}文件")
    except pd.errors.EmptyDataError:
        print("错误：Excel文件为空")
    except Exception as e:
        print("其他错误:", str(e))

if __name__ == "__main__":
    main() 